package com.baidu.threadPoolExcutor.threadInThreadTest;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadFactory {
    private static final int DEFAULT_QUEUE_SIZE = 100;
    private static final int DEFAULT_CORE_SIZE = 10;

    private int queueSize;
    private int coreSize;
    private String name;

    private List<ThreadPoolExecutor> executorList;

    /**
     * 创建线程池
     * @param queueSize
     * @param coreSize
     * @param name
     */
    public ThreadFactory(int queueSize, int coreSize, String name) {
        this.executorList = new ArrayList<>();

        this.queueSize = queueSize;
        this.coreSize = coreSize;
        this.name = name;

        for (int i = 0; i < coreSize; i++){
            ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                    1,
                    1,
                    0,
                    TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<>(queueSize)
            );

            this.executorList.add(threadPoolExecutor);
        }
    }

    /**
     * 包装execute方法 可以设置position
     * @param threadTask
     */
    public void execute(ThreadTask threadTask){
        // 将position与核心线程数对应
        int position = threadTask.position(this.coreSize);
        this.execute(threadTask, position);
    }

    /**
     * 相同的position使用相同的线程执行
     * @param runnable
     * @param position
     */
    public void execute(Runnable runnable, int position){
        ThreadPoolExecutor executor = this.executorList.get(position);
        executor.execute(runnable);
    }
}
